package cn.contentproviderandlistview;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

public class StuContentProvider extends ContentProvider {
    private StuOpenHelper openHelper;
    private static final String AUTOHORITY = "com.gdcp.student";
    private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        uriMatcher.addURI(AUTOHORITY, "student", 1);
    }

    @Override
    public boolean onCreate() {
        openHelper = new StuOpenHelper(getContext(), "stu.db", null, 1);
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs,
                        @Nullable String sortOrder) {
        SQLiteDatabase db = openHelper.getReadableDatabase();
        switch (uriMatcher.match(uri)) {
            case 1:
                Cursor cursor = db.query("student", projection, selection, selectionArgs, null, null, sortOrder);
                return cursor;
            default:
                break;
        }
        db.close();
        return null;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        SQLiteDatabase db = openHelper.getWritableDatabase();
        switch (uriMatcher.match(uri)) {
            case 1:
                db.insert("student", null, values);
                break;
            default:
                break;
        }
        db.close();
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = openHelper.getWritableDatabase();
        switch (uriMatcher.match(uri)) {
            case 1:
                db.delete("student", selection, selectionArgs);
                break;
            default:
                break;
        }
        db.close();
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = openHelper.getWritableDatabase();
        switch (uriMatcher.match(uri)) {
            case 1:
                db.update("student", values, selection, selectionArgs);
                break;
            default:
                break;
        }
        db.close();
        return 0;
    }
}
